package club.babyf.nativeai.demo.algorithm;

/**
 * RemoveNthFromEnd.
 *
 * @author zhanglei.
 * @date 2025/5/9 16:34.
 * @description 移除链表倒数第n位的元素.
 */
public class _7_RemoveNthFromEnd {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy;
        ListNode slow = dummy;

        // 快指针先移动n步
        for (int i = 0; i < n; i++) {
            if (fast == null) {
                return dummy.next; // n无效，直接返回原链表
            }
            fast = fast.next;
        }

        // 如果fast为null，说明n超过链表长度，返回原链表
        if (fast == null) {
            return dummy.next;
        }

        // 同步移动，直到fast指向最后一个节点
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }

        // 删除倒数第n个节点
        slow.next = slow.next.next;
        return dummy.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(head);
        _7_RemoveNthFromEnd removeNthFromEnd = new _7_RemoveNthFromEnd();
        ListNode listNode = removeNthFromEnd.removeNthFromEnd(head, 2);
        System.out.println(listNode);
    }

    public static class ListNode {

        int value;

        ListNode next;

        public ListNode(int value) {
            this.value = value;
        }

        public ListNode(int value, ListNode next) {
            this.value = value;
            this.next = next;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            ListNode current = this;
            while (current != null) {
                sb.append(current.value);
                ListNode next = current.next;
                if (next != null) {
                    sb.append(" -> ");
                }
                current = next;
            }
            return sb.toString();
        }

    }

}
